package homegroup.inc.servlets;

import homegroup.inc.dao.BookDAO;
import homegroup.inc.dto.Book;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;

/**
 * Created by stone on 04.12.2014.
 */
@WebServlet(name = "imageServlet", urlPatterns = {"/image"})
public class Servlet extends HttpServlet {

    @EJB
    BookDAO bookDAO;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        Book book = bookDAO.findByISBN(request.getParameter("isbn"));
//        String requestedImage = request.getPathInfo();
//        File image = new File(book.getCoverPath(), URLDecoder.decode(requestedImage, "UTF-8"));
        File image = new File(book.getCoverPath());
        String contentType = getServletContext().getMimeType(image.getName());
        response.reset();
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));
        Files.copy(image.toPath(), response.getOutputStream());
//        OutputStream out = response.getOutputStream();
//        InputStream input = new FileInputStream(image);
//        int read = 0;
//        byte[] readBytes = new byte[1024];
//        while ((read = input.read(readBytes)) != -1) {
//            out.write(readBytes, 0, read);
//        }
//        input.close();
//        out.close();
    }
}
